<template>
  <div class="container-fluid">
    <div class="row">
      <div class="col">
        <strong>创建题单</strong>
      </div>
    </div>
    <div class="row">
      <div class="col">
        <createdquestionbankVue ref="createdquestionbank" :ID="ID" :user="store.state.user" :is-admin="true">
        </createdquestionbankVue>
      </div>
    </div>

    <div class="row" :style="{ marginTop: '48px' }">
      <div class="col text-right">
        <el-button @click="submit" type="primary">保存</el-button>
        <router-link :to="{ name: '专题配置' }" custom v-slot="{ navigate }">
          <el-button type="info" @click="navigate">取消</el-button>
        </router-link>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ElMessage } from "element-plus";
import { computed, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import {
  asyncaddquestionbankteam,
  asyncchangequestionquestionbank,
  asynccreateorupdatequestionbank
} from "../../../api/index";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import createdquestionbankVue from "../../components/createdquestionbank/index.vue";

const route = useRoute()
const router = useRouter()

const ID = computed(() => {
  return route.query.ID as unknown as number
})
const store = useStore(Storekey)
const user = computed<Studycodemodel.Iuser>(() => {
  return store.getters.getuser;
});
const teamId = computed(() => {
  return user.value?.teamid
})

const createdquestionbank = ref()

async function submit() {
  try {
    const ruleForm = { ...createdquestionbank.value.ruleForm, teamid: teamId.value }
    // 创建题单
    const questionbank = await asynccreateorupdatequestionbank(ruleForm);
    ElMessage({
      message: "添加成功",
      type: "success",
    });
    // 题单赋值题目list
    const newvale: Studycodemodel.Iquestionquestionbank[] =
      createdquestionbank.value.questionid.map((v: { ID: any, df: number }, index: any) => {
        return {
          questionbankid: questionbank.ID,
          questionid: v.ID,
          sortindex: index,
          df: v.df
        };
      });
    await asyncchangequestionquestionbank({
      questionbankid: questionbank.ID as number,
      list: newvale,
    });

    // 添加team 题单
    await asyncaddquestionbankteam({ questionbankid: questionbank.ID, teamid: teamId.value })

    router.push({ name: '专题配置' })

  } catch (e: any) {
    ElMessage({
      message: e,
      type: "error",
    });
  }
}

</script>

<style scoped>
.container-fluid {
  --color-8c8c8c: #8c8c8c;
}
</style>